import { watchEffect, type Ref } from 'vue'

// 倒计时事件处理器函数
export function countdownEventHandler(time: Ref<number>, callback: () => void) {
  // 设置一个定时器，每秒钟执行一次
  const intervalId = setInterval(() => {
    if (time.value > 0) {
      // 如果倒计时时间大于0，减少时间
      time.value--
    } else {
      // 否则，清除定时器，调用回调函数
      clearInterval(intervalId)
      callback()
    }
  }, 1000)

  // 使用 watchEffect 来跟踪响应式引用的更改
  // 在响应式引用改变时，触发清理函数清除定时器
  watchEffect((onInvalidate) => {
    onInvalidate(() => clearInterval(intervalId))
  })
}
/**
 * time是倒计时，每down一秒触发change，当结束倒计时时调用callback
 * @param timeout
 * @param change
 * @param callback
 */
export function countdown(time: number, change: (current: number) => void, callback: () => void): void {
  let current = time

  const timer = setInterval(() => {
    // Call the change function with current countdown number
    change(current)

    current--

    // If the countdown has reached 0, clear the interval and call the callback function
    if (current < 0) {
      clearInterval(timer)
      callback()
    }
  }, 1000)
}
